<template>
  <div class="app-container">
    <!-- 操作区-->
    <!-- <div class="filter-container">
      <el-form ref="searchForm" size="mini" style="text-align:right">
        <el-form-item>
          <el-button type="primary" @click="confirmAll">全部
          </el-button>
          <el-button type="primary"  @click="initConfirm">有效
          </el-button>

        </el-form-item>
      </el-form>
    </div> -->

    <div class="tableHead">
      <div class="tabletitle">部门信息</div>
      <div class="btnGroup">
        <el-button-group>
          <el-button type="primary" icon="el-icon-search" @click="confirmAll">全部
          </el-button>
          <el-button type="primary" icon="el-icon-search" @click="initConfirm">有效
          </el-button>
        </el-button-group>
      </div>
    </div>
    <div class="filter-container">
      <el-form ref="form" :model="form" :rules="rules" inline size="mini" label-width="100px">
        <el-container>
          <el-aside>
            <el-tree v-loading="loading" ref="tree" :data="jsonTree" :default-expanded-keys="[1]" node-key="id" style="min-width: 100%; width: 75%;">
              <span slot-scope="{ node, data }" class="custom-tree-node" @click="handleNodeClick(data)">
                <span>{{ node.data.text }}</span>
                <span>
                  <el-button type="text" size="mini" @click.stop="()=>append(data)">
                    新增
                  </el-button>
                </span>
              </span>
            </el-tree>
          </el-aside>
          <div class="searchform">
            <el-main ref="form" :model="form" :rules="rules">
              <el-form-item label="上级组织" prop="parent_org_id">
                <el-select v-model="form.parent_org_id" disabled="disabled" placeholder="请选择" class="form-input">
                  <el-option v-for="item in parentOrgOptions" :key="item.ORGDEPT_ID" :label="item.ORG_NAME" :value="item.ORGDEPT_ID"/>
                </el-select>
              </el-form-item>
              <el-form-item label="组织ID" prop="orgDeptId">
                <el-input v-model="form.orgdept_id" disabled="disabled" size="mini" class="form-input" placeholder="组织ID" />
              </el-form-item>
              <el-form-item label="组织名称" prop="org_name">
                <el-input v-model="form.org_name" size="mini" class="form-input" placeholder="组织名称" />
              </el-form-item>
              <el-form-item label="组织类型" prop="org_type">
                <r-select v-model="form.org_type" type="1506" class="form-input" placeholder="组织类型"/>
              </el-form-item>
              <el-form-item label="是否有效" prop="is_valid">
                <r-select id="is_valid" v-model="form.is_valid" type="1001" class="form-input"/>
              </el-form-item>
              <el-form-item label="名称缩写" prop="org_short_name">
                <el-input v-model="form.org_short_name" size="mini" class="form-input" placeholder="名称缩写" />
              </el-form-item>
              <el-form-item label="组织描述" prop="orgDesc">
                <el-input v-model="form.org_desc" rows="3" class="form-input" size="medium" type="textarea" placeholder="组织描述" />
              </el-form-item>
              <el-form-item v-if="false" label="数据来源" prop="dataSource">
                <r-select v-model="form.data_source" type="1045" class="form-input"/>
              </el-form-item>

              <el-form-item v-if="false" label="所属组织" prop="dataType">
                <r-select v-model="form.data_type" :value="10461001" type="1046" placeholder="所属组织" class="form-input"/>
              </el-form-item>
              <div align="center">
                <el-button type="primary" icon="el-icon-plus" @click="editConfirm">保 存</el-button>
              </div>
            </el-main>
          </div>
        </el-container>

      </el-form>
    </div>
  </div>
</template>

<script>
import { getJsonTree } from '@/utils/index'
import {
  getDept,
  getTree,
  getSuper,
  addDept,
  updateDept
} from '@/api/admin/org/deptInfo'
import formMixins from '@/mixins/formMixins'
import rSelect from '@/components/Select/Select'
import _ from 'lodash'
// import { mapGetters } from 'vuex'
// import { addTreeNode, removeTreeNode, updateTreeNode } from '@/api/base/users'

export default {
  name: 'DeptInfoManage',
  components: {
    rSelect
  },
  mixins: [formMixins],
  data() {
    return {
      model: ['1'],
      form: {},
      tree: [],
      parentList: [],
      parentListId: [],
      childrenListId: [],
      rules: {
        parent_org_id: [
          { required: true, message: '请选择上级组织', trigger: 'blur' }
        ],
        org_name: [
          { required: true, message: '请填写组织名称', trigger: 'blur' }
        ],
        org_type: [
          { required: true, message: '请选择组织类型', trigger: 'blur' }
        ],
        is_valid: [
          { required: true, message: '请选择是否有效', trigger: 'blur' }
        ],
        org_short_name: [
          { required: true, message: '请填写名称缩写', trigger: 'blur' }
        ]
      },
      parentOrgOptions: [
        { required: true, message: '请选择上级组织', trigger: 'blur' }
      ],
      defaultProps: {
        children: 'children',
        label: 'text'
      }
    }
  },
  computed: {
    jsonTree() {
      this.tree.forEach(el => (el.parentId = el.parent))
      return getJsonTree(this.tree)
    }
  },
  mounted() {
    this.getSuper()
    this.initConfirm()
  },
  created() {
    this.searchTree()
  },
  methods: {
    // 加载树
    getTrees(url) {
      getTree(url)
        .then(res => {
          this.deleteRes(res)
          this.tree = res
          this.searchHandle(res[0].id)
        })
        .catch(err => {
          // table.complete()
        })
    },
    // 删除无效数据
    deleteRes(res) {
      const result = []
      for (let i = 0; i < res.length && res[i].id != null; i++) {
        const pid = res[i].parent
        const oid = res[i].id
        result[oid] = pid
      }
      for (let j = 0; j < res.length; j++) {
        if (res[j].parent === '#') continue
        if (res[j] && result[res[j].parent] === null) {
          const index = j
          j = 0
          delete result[res[index].id]
          res.splice(index, 1)
        }
      }
    },
    // 获取上级组织下拉数据
    getSuper() {
      getSuper()
        .then(res => {
          this.parentOrgOptions = res
        })
        .catch(err => {
          // table.complete()
        })
    },
    // 按照id查询
    searchHandle(id) {
      getDept(id)
        .then(res => {
          this.form = _.cloneDeep(res)
        })
        .catch(err => {
          // table.complete()
        })
    },
    // 树  全部
    confirmAll() {
      const url = `/basedata/orgs`
      this.getTrees(url)
    },
    // 树 页面加载初始化  有效
    initConfirm() {
      const url = `/basedata/orgs/getIsValid/Orgs`
      this.getTrees(url)
    },
    // 点击树  查询数据
    handleNodeClick(data) {
      this.searchHandle(data.id)
    },
    editConfirm() {
      //  新增
      this.form.parentOrgId = this.form.parent_org_id
      this.form.orgDeptId = this.form.orgdept_id
      this.form.orgName = this.form.org_name
      this.form.orgType = this.form.org_type
      this.form.isValid = this.form.is_valid
      this.form.orgShortName = this.form.org_short_name
      this.form.orgDesc = this.form.org_desc
      this.form.dataSource = this.form.data_source
      this.form.dataType = this.form.data_type
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.orgdept_id === undefined) {
            addDept(this.form)
              .then(res => {
                this.$message({
                  message: '新增成功',
                  type: 'success'
                })
                this.initConfirm()
              })
              .catch(err => {
                // table.complete()
              })
            //  修改
          } else {
            // this.tree.forEach(function(el) {
            //   this.id.push(el.id);
            //   this.parentid.push(el.parentid);
            // });
            this.parentListId = []
            this.buildParentList(this.tree)
            this.findParent(this.form.parent_org_id)
            this.findChildren(this.form.orgdept_id)
            let chickIdRange = this.form.orgdept_id
            const child = this.childrenListId
            const parent = this.parentListId
            const isValid = this.form.is_valid
            // 为无效时
            if (isValid === '10011002' && child) {
              for (var i = 0; i < child.length; i++) {
                if (child[i] === '') {
                  chickIdRange += child[i]
                } else {
                  chickIdRange += ',' + child[i]
                }
              }
            } else if (isValid === '10011001' && parent) {
              for (let i = 0; i < child.length; i++) {
                if (child[i] === '') {
                  chickIdRange += child[i]
                } else {
                  chickIdRange += ',' + child[i]
                }
              }
              for (let i = 0; i < parent.length; i++) {
                if (parent[i] === '#') {
                  chickIdRange += ''
                } else {
                  chickIdRange += ',' + parent[i]
                }
              }
            }
            updateDept(chickIdRange, this.form)
              .then(res => {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.loading = false
                this.initConfirm()
              })
              .catch(err => {
                // this.$message.error(err.response.data.errorMsg);
              })
          }
        }
      })
    },
    // 排列所有parentId和id对应关系 id为key parentId为值
    buildParentList(arr) {
      arr.forEach(g => {
        if (g.parentId || g.parent) {
          const pid = g['parentId'] === null ? g.parent : g['parentId']
          const oid = g['id']
          this.parentList[oid] = pid
        }
        if (g.children) this.buildParentList(g['children'])
      })
    },
    // 根据当前节点id获取parentId
    findParent(idx) {
      if (this.parentList[idx]) {
        const pid = this.parentList[idx]
        this.parentListId.push(pid)
        this.findParent(pid)
      }
    },
    // 根据当前节点id获取ChildrenId
    findChildren(idx) {
      const ChildrenId = this.findKey(idx)
      for (let i = 0; i < ChildrenId.length; i++) {
        this.childrenListId.push(ChildrenId[i])
        this.findChildren(ChildrenId[i])
      }
    },
    findKey(idx) {
      const ChildrenId = []
      this.parentList.forEach(function(value, key) {
        if (idx === value) {
          ChildrenId.push(key)
        }
      })
      return ChildrenId
    },
    // 获取功能树
    searchTree() {
      const url = `/basedata/orgs/getIsValid/Orgs`
      this.loading = true
      getTree(url)
        .then(res => {
          this.loading = false
          this.tree = res
        })
        .catch(err => {
          this.loading = false
        })
    },
    // 点击树新增
    append(data) {
      this.form = {}
      this.form.data_type = 10461001
      this.form.data_source = 10451001
      // 如果上级部门为无效不能修改
      // if (data.is_valid === "10011002") {
      // $("#orgType").attr("disabled","disabled");

      // }
      this.form.parent_org_id = Number(data.id)
      this.form.is_valid = 10011001
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
